package com.wocao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wocao.entity.ReqBody;
import com.wocao.entity.ZyBuilding;
import com.wocao.entity.ZyUnit;
import com.wocao.mapper.ZyBuildingMapper;
import com.wocao.mapper.ZyUnitMapper;
import com.wocao.service.ZyUnitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wocao.utils.ExcelUtil;
import com.wocao.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 单元  服务实现类
 *
 * @since 2023-12-02
 */
@Service
public class ZyUnitServiceImpl extends ServiceImpl<ZyUnitMapper, ZyUnit> implements ZyUnitService {
    @Autowired
    private ZyUnitMapper zyUnitMapper;
    @Autowired
    private ZyBuildingMapper zyBuildingMapper;

    @Override
    public Page<ZyUnit> selectUnitAll(Page page, ReqBody reqBody) {
        return zyUnitMapper.selectUnitAll(page,reqBody.getUnitName(),reqBody.getUnitCode(),reqBody.getUnitHaveElevator(),reqBody.getBuildingId(),reqBody.getComId());
    }

    @Override
    public void derive(HttpServletResponse response, String[] unitIds) throws IOException {
        List<ZyUnit> zyUnits = new ArrayList<>();
        for (int i = 0; i < unitIds.length; i++) {
            ZyUnit zyUnit = zyUnitMapper.selectUnityById(unitIds[i]);
            zyUnits.add(zyUnit);
        }
        ExcelUtil.export(response,ZyUnit.class,zyUnits);
    }

    @Override
    public void unitAdd(ZyUnit zyUnit) {
        ZyBuilding zyBuilding = zyBuildingMapper.selectById(zyUnit.getBuildingId());
        zyUnit.setCommunityId(zyBuilding.getCommunityId());
        zyUnit.setUpdateTime(LocalDateTime.now());
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(8, 1);
        Long nextId = idWorker.nextId();
        zyUnit.setUnitId(nextId.toString());
        zyUnitMapper.insert(zyUnit);
    }

    @Override
    public void unitEdit(ZyUnit zyUnit) {
        zyUnit.setUpdateTime(LocalDateTime.now());
        ZyBuilding zyBuilding = zyBuildingMapper.selectById(zyUnit.getBuildingId());
        zyUnit.setCommunityId(zyBuilding.getCommunityId());
        zyUnitMapper.updateById(zyUnit);
    }

    @Override
    public List<ZyUnit> getUnitsByBuildingId(String buildingId) {
        LambdaQueryWrapper<ZyUnit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZyUnit::getBuildingId, buildingId);
        return zyUnitMapper.selectList(queryWrapper);
    }
}
